package net.zoneland.knowledge.exceptions;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonParseException;

import net.zoneland.knowledge.constant.ResponseMessage;
import net.zoneland.knowledge.constant.WebConstant;
import net.zoneland.knowledge.model.ResponseModel;

/**
 * 全局异常处理类.
 * @author bcc
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * logger.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    static {
        Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
            LOGGER.error("thread catch exception ", e);
        });
    }

    /**
     * 异常处理方法.
     * @param exception exception
     * @return 响应
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseBody
    public ResponseModel exceptionHandler(final HttpMessageNotReadableException exception) {
        LOGGER.error("GlobalExceptionHandler HttpMessageNotReadableException", exception);
        ResponseModel rs = new ResponseModel();
        rs.setResult(WebConstant.RESULT_FAIL);
        rs.setMessage(ResponseMessage.REQUEST_PARAM_ERROR);
        return rs;
    }
    /**
     * 异常处理方法.
     * @param exception exception
     * @return 响应
     */
    @ExceptionHandler(NumberFormatException.class)
    @ResponseBody
    public ResponseModel exceptionHandler(final NumberFormatException exception) {
        LOGGER.error("GlobalExceptionHandler NumberFormatException", exception);
        ResponseModel rs = new ResponseModel();
        rs.setResult(WebConstant.RESULT_FAIL);
        rs.setMessage(ResponseMessage.REQUEST_PARAM_FORMAT_ERROR);
        return rs;
    }
    /**
     * 异常处理方法.
     * @param exception exception
     * @return 响应
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseModel exceptionHandler(final Exception exception) {
        LOGGER.error("GlobalExceptionHandler exceptionHandler", exception);
        ResponseModel rs = new ResponseModel();
        rs.setResult(WebConstant.RESULT_FAIL);
        if (exception instanceof JsonParseException) {
            rs.setMessage("请求参数不正确");
        } else {
            rs.setMessage(exception.getMessage());
        }
        return rs;
    }
}
